package me.jiatao.baselibrary.ui.fragment

import android.view.View
import android.widget.Toast
import me.jiatao.baselibrary.common.BaseApplication
import me.jiatao.baselibrary.injection.component.ActivityComponent
import me.jiatao.baselibrary.injection.component.DaggerActivityComponent
import me.jiatao.baselibrary.injection.module.ActivityModule
import me.jiatao.baselibrary.injection.module.LifecycleProviderModule
import me.jiatao.baselibrary.mvp.presenter.BasePresenter
import me.jiatao.baselibrary.mvp.view.BaseView
import me.jiatao.baselibrary.widgets.ProgressLoading
import javax.inject.Inject

/**
 *  Fragment基类，业务相关
 */
abstract class BaseMvpFragment<V : BaseView, P : BasePresenter<V>> : BaseFragment(), BaseView {

    @Inject
    lateinit var mPresenter: P
    lateinit var mActivityComponent: ActivityComponent

    private lateinit var mLoadingDialog: ProgressLoading

    override fun initView(view: View) {
        super.initView(view)
        /**
         * 注入Activity对象
         */
        initActivityInjection()
        injectComponent()
        //设置View引用
        @Suppress("UNCHECKED_CAST")
        mPresenter.attachView(this as V)

        //初始加载框
        mLoadingDialog = ProgressLoading.create(mActivity)
    }

    override fun onDestroyView() {
        mPresenter.detachView()
        super.onDestroyView()
    }


    /**
     *  初始化Activity级别Component
     */
    private fun initActivityInjection() {
        mActivityComponent = DaggerActivityComponent.builder()
            .appComponent((mActivity.application as BaseApplication).appComponent)
            .activityModule(ActivityModule(mActivity))
            .lifecycleProviderModule(LifecycleProviderModule(this))
            .build()
    }

    /**
     *  Dagger注册
     */
    protected abstract fun injectComponent()

    /**
     *  弹出消息
     */
    protected fun showToast(message: String) {
        Toast.makeText(mActivity, message, Toast.LENGTH_SHORT).show()
    }


    /**
     *  显示加载框，默认实现
     */
    override fun showLoading() {
        mLoadingDialog.showLoading()
    }

    /**
     *   隐藏加载框，默认实现
     */
    override fun hideLoading() {
        mLoadingDialog.hideLoading()
    }

    /**
     *   错误信息提示，默认实现
     */
    override fun onError(text: String) {
        showToast(text)
    }
}
